package com.favorites.service.impl;

import com.favorites.domain.Collect;
import com.favorites.domain.FavoritesNodes;
import com.favorites.domain.enums.CollectType;
import com.favorites.domain.enums.IsDelete;
import com.favorites.repository.CollectRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.favorites.domain.Favorites;
import com.favorites.repository.FavoritesRepository;
import com.favorites.service.FavoritesService;
import com.favorites.utils.DateUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("favoritesService")
public class FavoritesServiceImpl implements FavoritesService {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FavoritesRepository favoritesRepository;
    @Autowired
    private CollectRepository collectRepository;

    @Override
    public Favorites saveFavorites(Long userId, String name, Long preId) {
        Favorites favorites = new Favorites();
        favorites.setName(name);
        favorites.setUserId(userId);
        favorites.setPreId(preId);
        favorites.setCount(0l);
        favorites.setPublicCount(10l);
        favorites.setCreateTime(DateUtils.getCurrentTime());
        favorites.setLastModifyTime(DateUtils.getCurrentTime());
        favoritesRepository.save(favorites);
        return favorites;
    }

    /**
     * 保存
     *
     * @return
     */
    public Favorites saveFavorites(Collect collect) {
        Favorites favorites = new Favorites();
        favorites.setName(collect.getNewFavorites());
        favorites.setUserId(collect.getUserId());
        favorites.setCount(1l);
        if (CollectType.PUBLIC.name().equals(collect.getType())) {
            favorites.setPublicCount(1l);
        } else {
            favorites.setPublicCount(10l);
        }
        favorites.setCreateTime(DateUtils.getCurrentTime());
        favorites.setLastModifyTime(DateUtils.getCurrentTime());
        favoritesRepository.save(favorites);
        return favorites;
    }


    public void countFavorites(long id) {
        Favorites favorite = favoritesRepository.findById(id);
        Long count = collectRepository.countByFavoritesIdAndIsDelete(id, IsDelete.NO);
        favorite.setCount(count);
        Long pubCount = collectRepository.countByFavoritesIdAndTypeAndIsDelete(id, CollectType.PUBLIC, IsDelete.NO);
        favorite.setPublicCount(pubCount);
        favorite.setLastModifyTime(DateUtils.getCurrentTime());
        favoritesRepository.save(favorite);
    }

    /**
     * 获取用户书签tree
     * @param userId
     * @return
     * @author Jack126
     * @date 2020-12-22
     */
    public List<FavoritesNodes> getFavoritesList(Long userId) {
        List<Favorites> rootMenu = favoritesRepository.findByUserId(userId);
        List<FavoritesNodes> menuList = new ArrayList<FavoritesNodes>();
        Map<Long, Long> tags = new HashMap<>();
        for (int i = 0; i < rootMenu.size(); i++) {
            // 一级菜单没有parentId
            if (rootMenu.get(i).getPreId().equals(0) || 0 == rootMenu.get(i).getPreId()) {
                FavoritesNodes favoritesNodes = new FavoritesNodes();
                favoritesNodes.setText(rootMenu.get(i).getName());
                favoritesNodes.setHref("/standard/"+rootMenu.get(i).getId()+"/0");
                favoritesNodes.setId(rootMenu.get(i).getId());
                menuList.add(favoritesNodes);
            } else {
                if (tags.containsKey(rootMenu.get(i).getPreId())) {
                    tags.put(rootMenu.get(i).getPreId(), tags.get(rootMenu.get(i).getPreId()) + 1);
                } else {
                    tags.put(rootMenu.get(i).getPreId(), 1l);
                }
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (FavoritesNodes menu : menuList) {
            Long[] tagsNum = {tags.get(menu.getId())};
            menu.setTags(tagsNum);
            menu.setNodes(getChild(menu.getId(), rootMenu, tags));
        }

        return menuList;
    }

    /**
     * 递归获得书签tree-children
     * @param id
     * @param rootMenu
     * @param tags
     * @return
     * @author Jack126
     * @date 2020-12-22
     */
    private List<FavoritesNodes> getChild(Long id, List<Favorites> rootMenu, Map<Long, Long> tags) {
        List<FavoritesNodes> favoritesNodesList = new ArrayList<>();
        for (Favorites favorites : rootMenu) {
            if (id.equals(favorites.getPreId())) {
                FavoritesNodes favoritesNodes = new FavoritesNodes();
                favoritesNodes.setText(favorites.getName());
                favoritesNodes.setHref("/standard/"+favorites.getId()+"/0");
                favoritesNodes.setId(favorites.getId());
                favoritesNodesList.add(favoritesNodes);
            }
        }
        for (FavoritesNodes favoritesNodes : favoritesNodesList) {
            Long[] tagsNum = new Long[0];
            if (null == tags.get(favoritesNodes.getId())) {
                tagsNum = new Long[]{0l};
            } else {
                tagsNum = new Long[]{tags.get(favoritesNodes.getId())};
            }
            favoritesNodes.setTags(tagsNum);
            favoritesNodes.setNodes(getChild(favoritesNodes.getId(), rootMenu, tags));
        }
        if (favoritesNodesList.size() == 0) {
            return null;
        }
        return favoritesNodesList;
    }
}